<template>

  <div class="my-data" ref="myData">

    <!-- 数据上传按钮，数据搜索框 -->
    <div style="border-bottom:1px solid #ddd;" class="option" v-if="!isEmpty">

      <div class="option-container" :class="[ isListView ? 'adaption-list' : 'adaption']">
        <ul class="resource-switch clearfix">
          <li @click="handleResSwitch('上传资源', $event)" class="private-upload-res active"><span>上传资源</span></li>
          <!-- <li @click="handleResSwitch('申请资源', $event)"><span>申请资源</span></li> -->
        </ul>
        <div class="range">
          <span @click="changeSortTime">
            <i class="iconfont" :class="`icon-sort-${sortTime}`"></i> 时间
          </span>
          <span @click="changeRangeType">
            <template v-if="isListView"><i class="iconfont icon-tiling"></i> 平铺</template>
            <template v-else><i class="iconfont icon-menu"></i> 列表</template>
          </span>
        </div>

        <div class="search">
          <input type="text" class="input-search" v-model="search" v-on:keyup.enter="query" placeholder="搜索">
          <div class="btn-search" @click="query">
            <i class="iconfont icon-loading icon-spin" v-show="isLoading"></i>
            <i class="iconfont icon-search" v-show="!isLoading"></i>
          </div>
        </div>

        <div class="upload-data" @click="upload">
          <i class="iconfont icon-upload"></i>
          <span>上传数据</span>
        </div>
      </div>
    </div>

    <div style="padding-top:100px;" class="data-list-container">

      <div v-if="isEmpty" class="no-data">
        <img src="../../../static/img/no-data.png">
        <div class="no-data-tip">您还未上传过数据</div>
        <div class="empty-handler" @click="upload">上传数据</div>
      </div>

      <template v-else>
        <div class="wrapper-body">
          <div v-show="isListView" class="list-view-header" :class="[ isListView ? 'adaption-list' : 'adaption']">
            <div class="name">数据名称</div>
            <div class="data-count">数据量</div>
            <div class="date">上传日期</div>
            <div class="data-option">操作</div>
          </div>
          <g-scrollbar class="data-vertical-scroll" :class="{'with-header': isListView}">
            <div :class="[ isListView ? 'adaption-list' : 'adaption']">
              <div class="datas-content">
                <ul class="data-view">
                  <component v-for="(data,index) in dataList" :currentMenu="currentMenu" :is="view" :dataType="dataType" type="private" :data="data" :index="index" :key="data.uid" :isPrivate="true" v-on:open="open" v-on:remove="remove" v-on:data-preview="preview" v-on:data-share="share" v-on:data-store="store" v-on:set-current-menu="setCurrentMenu">
                  </component>
                </ul>

                <div class="add-more-wrapper">
                  <button class="add-more" v-show="hasNext" @click="addMore()" :disabled="isLoading">
                    <span v-show="!isLoading">
                      <i class="iconfont icon-flip-down"></i> 加载更多
                    </span>
                    <span v-show="isLoading">
                      <i class="iconfont icon-loading spin"></i> 加载中…
                    </span>
                  </button>
                </div>
              </div>
            </div>
          </g-scrollbar>
        </div>
      </template>

    </div>

    <transition-group name="fade">
      <div :key="'upload-georeference-container'">
        <upload v-if="openUpload"></upload>
        <georeference :uid="dataUid" v-if="openGeoreference"></georeference>
      </div>
      <data-preview :key="'preview'" :base-path="basePath" :is-private="true" :previewData="previewData" @close-preview="closePreview" v-if="openPreview" :dataType="dataType"></data-preview>
      <data-share v-if="openShare" key='share' :shareData="shareData" :groups="groups" v-on:close-share="closeShare" :shareDataName="shareDataName"></data-share>
    </transition-group>

  </div>

</template>

<script>
import Bus from "@/utils/event_bus";
import TilingWrapper from "./tiling-wrapper";
import ListWrapper from "./list-wrapper";
import DataPreview from "components/preview/data-preview";
import GScrollbar from "components/common/g-scrollbar";
import Upload from "components/upload/upload";
import Georeference from "./georeference";
import DataShare from "./data-share";
import GButton from "@/components/common/g-button";
import {
  data as dataAPI,
  organization as orgAPI,
  bookmark as bookmarkAPI
} from "@/api";

import newConfig from "@/config/newConfig.js";

const viewTypes = ["map", "table", "metadata"];
const limit = 60;

export default {
  name: "private-data",
  components: {
    ListWrapper,
    TilingWrapper,
    DataPreview,
    Upload,
    Georeference,
    DataShare,
    GButton,
    GScrollbar
  },

  data: function() {
    const dataType = "data";
    return {
      dataType,
      isLoading: false,
      dataList: [],
      page: 0,
      hasNext: false,
      search: "",
      previewData: null,
      openPreview: false,
      openUpload: false,
      openGeoreference: false,
      shareData: "",
      shareDataName: "", //数据名称有可能已经更改，再未刷新数据列表之前，要传入改过的数据名
      openShare: false,
      currentMenu: "", //用于控制dataWrapper中打开的菜单
      dataUid: null,

      isEmpty: false,
      sortTime: "desc",
      view: "tiling-wrapper",
      groups: [],
      basePath: "/data/private-data",

      queryParams: {
        type: "uploadResource",
        ownerType: "3"
      }
    };
  },

  created: function() {
    // 检查URL中是否已经包含打开特定数据和视图的参数
    let params = this.$route.params;

    if (Object.keys(params).length > 0 && params.uid && params.view) {
      this.openDataView(params.uid, params.view);
    }

    Bus.$on("close-upload-panel", () => {
      this.openUpload = false;
    });

    Bus.$off("upload-success");
    Bus.$on("upload-success", uid => {
      this.openUpload = false;
      this.openGeoreference = true;
      this.dataUid = uid;
      // 刷新数据列表
      this.getData(0, true);
    });

    Bus.$off("georeference-cancel");
    Bus.$on("georeference-cancel", () => {
      this.openGeoreference = false;
      // 刷新数据列表
      this.getData(0, true);
    });

    Bus.$off("georeference-success-mydata");
    Bus.$on("georeference-success-mydata", uid => {
      this.openGeoreference = false;
      this.getData(0, true);
      return;
    });

    Bus.$off("close");
    Bus.$on("close", () => {
      this.openUpload = false;
    });

    Bus.$off("geofile-upload-success");
    Bus.$on("geofile-upload-success", () => {
      this.getData(0, true);
    });

    Bus.$off("close-data-upload");
    Bus.$on("close-data-upload", () => {
      this.openUpload = false;
    });
  },

  props: {
    orgUid: String
  },

  async mounted() {
    await this.getData(0);
    await this.getGroups();
    this.$emit("on-view-load");

    Bus.$on("reset-group", async () => {
      await this.getGroups();
    });
  },

  computed: {
    isListView() {
      return !!(this.view === "list-wrapper");
    }
  },

  beforeRouteEnter(to, from, next) {
    next(vm => {});
  },

  beforeRouteLeave: function(to, from, next) {
    this.closePreview();
    next();
  },

  directives: {
    focus: {
      componentUpdated: function(el, { value }) {
        if (value) {
          el.focus();
        }
      }
    }
  },

  methods: {
    open() {},

    async getGroups() {
      if (!this.orgUid) {
        return;
      }

      let result = await orgAPI.summary(this.orgUid);

      if (result.data.code != 0) {
        //this.$message.error('获取群组失败');
        return;
      }

      let data = result.data.data;
      let groups = data.groups;
      let members = data.members;

      let arr = [];

      groups.forEach(n => {
        arr.push({
          name: n.name,
          key: n.uid,
          icon: "group",
          count: n.members
        });
      });

      this.groups = [].concat(arr);
    },

    changeRangeType() {
      if (this.loading || this.isEmpty) return;
      this.view =
        this.view === "list-wrapper" ? "tiling-wrapper" : "list-wrapper";
    },

    changeSortTime() {
      if (this.loading) return;

      this.sortTime = this.sortTime === "desc" ? "asc" : "desc";
      this.getData(0, true);
    },

    query() {
      if (this.isLoading) {
        return;
      }

      this.getData(0, true);
    },

    addMore() {
      if (this.hasNext) {
        this.page += 1;
        this.getData(this.page);
      }
    },

    setCurrentMenu(menu) {
      this.currentMenu = menu;
    },

    /**
     * 获取用户数据
     */
    getData(page = 0, clear) {
      this.page = page;
      this.isLoading = true;

      let params = {
        limit,
        page: page,
        search: this.search,
        timeOrder: this.sortTime
      };
      if (this.queryParams.type == "uploadResource") {
        this.requestUploadRes(params, clear);
      } else if (this.queryParams.type == "resourceApply") {
        let _params = {
          page: params.page,
          rows: params.limit,
          sort: "regDate",
          order: params.timeOrder.toUpperCase()
        };
        if (params.search != "") {
          _params.name = params.search;
        }
        this.requestApplyRes(_params, clear);
      }
    },
    //申请资源
    requestApplyRes(params, clear) {
      let url = `${newConfig.api}/${this.queryParams.type}/query/ownertype/${
        this.queryParams.ownerType
      }`;
      this.$root.$http
        .get(url, {
          params: params
        })
        .then(response => {
          // console.log(response);
          let data = response.data.data;
          data.items.forEach(item => {
            item.uid = item.ghid;
          });

          this.isLoading = false;
          this.hasNext = data.hasNext;
          this.isEmpty = false;
          if (!data.items || data.items.length <= 0) {
            this.dataList = [];
          } else {
            this.dataList = this.dataList.concat(data.items);
          }
          //this.isEmpty = !this.dataList.length;
          //关闭加载界面
          this.$emit("change-loading", { add: true, key: "private-data" });
        })
        .catch(error => {
          this.isLoading = false;
          this.$message.error("获取数据失败");
        });
    },
    //上传资源
    requestUploadRes(params, clear) {
      dataAPI.list(
        params,
        res => {
          if (Number(res.data.code) != 0) {
            let msg = res.data.msg;

            if (msg) {
              this.$message.error(msg);
            }
            return;
          }

          let data = res.data.data;

          // console.log(data);

          if (clear) {
            if (data.items.length != 0) {
              this.dataList = [];
            } else {
              this.$message.warning("未找到相应内容");
              this.isLoading = false;
              return;
            }
          }

          this.isLoading = false;
          this.dataList = this.dataList.concat(data.items);

          this.hasNext = data.hasNext;

          this.isEmpty = !this.dataList.length;

          //关闭加载界面
          this.$emit("change-loading", { add: true, key: "private-data" });

          return;
        },
        err => {
          this.isLoading = false;
          this.$message.error("获取数据失败");
          return;
        }
      );
    },
    preview(data) {
      this.previewData = data;
      this.openPreview = true;
    },

    closePreview() {
      this.previewData = null;
      this.openPreview = false;
    },

    share(data, name) {
      let shared = data.shareStatus;

      if (shared === "shared") {
        this.$message.warning("该数据已分享过，无法重复分享");
        return;
      }
      this.shareData = data;
      this.shareDataName = name;
      this.openShare = true;
    },

    closeShare: function() {
      this.shareData = "";
      this.openShare = false;
    },

    store(data) {
      this.$emit("data-store", data);
    },

    upload() {
      this.openUpload = true;
    },

    remove(data, dataName) {
      let uid = data.uid;
      let success = false;

      let promise = this.$confirm(
        `数据删除后不可恢复，确认删除数据“${dataName}”？`,
        "删除",
        {
          type: "warning",
          confirmButtonType: "danger",
          confirmButtonText: "删除",
          // parent: this.$refs.myData,
          beforeClose: async (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = "删除中...";
              instance.cancelButtonDisabled = true;

              let result = await bookmarkAPI.getStored(uid);
              if (result && result.data.code === 0) {
                let data = result.data.data;
                let stored = data.bookmarks;
                Bus.$emit("clear-bookmark-data", stored);
              }

              let removeResult = await dataAPI.remove(uid);
              if (removeResult && removeResult.data.code === 0) {
                success = true;
                Bus.$emit("summary-reset");
                Bus.$emit("group-data-reset");
                done();
              } else {
                this.$message.error("删除失败");
                done();
                return;
              }

              instance.confirmButtonLoading = false;
            } else {
              done();
            }
          }
        }
      );

      promise
        .then(async () => {
          if (!success) {
            this.$message.error("删除失败");
            return;
          }
          let dataList = this.dataList;
          let index = dataList.findIndex(item => {
            return item.uid == uid;
          });

          if (index >= 0) {
            dataList.splice(index, 1);
            this.$message.success("删除成功");

            let len = dataList.length;

            if (len === 0 && !this.hasNext) {
              this.isEmpty = true;
              return;
            }

            if (len === 0 && this.hasNext) {
              this.getData(0);
            }
          }

          Bus.$emit("clear-bookmark-count");
        })
        .catch(() => {
          // this.$message.error('取消')
        });
    },

    async openDataView(uid, viewType) {
      // 获取数据详情
      let dataInfo = await this.getDataInfo(uid);

      if (!dataInfo) {
        return;
      }

      if (viewTypes.indexOf(viewType) === -1) {
        viewType = "map";
      }

      let customPreviewData = {
        uid: uid,
        geometryType: dataInfo.geomType,
        extent: dataInfo.extent,
        name: dataInfo.name,
        count: dataInfo.count,
        view: viewType,
        convertEnd: dataInfo.geomType === null ? false : true,
        isPrivate: true
      };

      // 打开预览窗口
      this.openPreview = true;
      this.previewData = customPreviewData;
    },

    /**
     * 获取数据详情
     * @param string uid 数据UID
     */
    async getDataInfo(uid) {
      let dataInfo = await dataAPI.info(uid);

      if (dataInfo.data.code === 0) {
        return dataInfo.data.data;
      }

      this.$message.error("您请求的数据不存在");

      return null;
    },
    handleResSwitch(type, event) {
      let currentTarget = event.currentTarget;
      if (currentTarget.classList.contains("active")) {
        return;
      }
      let list = currentTarget.parentNode.querySelectorAll("li");
      for (let item of list) {
        item.classList.remove("active");
      }
      currentTarget.classList.add("active");
      let params = {
        type: "uploadResource",
        ownerType: "3"
      };
      if (type == "申请资源") {
        params.type = "resourceApply";
      }
      this.queryParams = params;
      this.dataList = [];
      let isPrivateUploadData = document
        .querySelector(".private-upload-res")
        .classList.contains("active");
      this.$store.state.isPrivateUploadData = isPrivateUploadData;

      this.getData();
    }
  }
};
</script>

<style lang="scss" rel="stylesheet/scss">
@import "common";

@media screen and (max-width: 1200px) {
  .upload-data {
    width: 64px !important;

    > span {
      display: none !important;
    }

    > i {
      display: block !important;
    }
  }
}

@media screen and (max-width: 900px) {
  .search {
    display: none !important;
  }
}

.my-data {
  height: 100%;
  width: 100%;
  font-size: 12px;
  position: relative;
  @include box-sizing(border-box);

  //     .list-table-wrapper{

  //         @media screen and (max-width: 1050px) {
  //            	min-width: 720px;
  // -ms-overflow-style: -ms-autohiding-scrollbar;
  // -webkit-overflow-scrolling: touch;
  //         }

  //     }

  > .option {
    width: 100%;
    position: absolute;
    top: 0;
    padding: 18px 0;
    @include box-shadow(0 4px 6px 2px rgba(255, 255, 255, 0.3));

    .option-container {
      overflow: hidden;

      .range {
        display: block;
        float: right;
        width: 160px;
        color: $gray;
        padding: 6px 0;
        cursor: pointer;
        text-align: right;
        @include user-select(none);
        > span {
          line-heigth: 32px;
          height: 32px;
          text-align: center;
          font-size: 14px;
          padding: 0 5px;

          &:hover {
            color: $primary;
          }
        }
      }

      .search {
        float: right;
        width: 210px;
        color: $gray;
        position: relative;

        .input-search {
          width: 210px;
          height: 32px;
          padding: 6px 42px 6px 12px;
          border: 1px solid $bdGray;
          border-radius: 16px;

          &:focus {
            border-color: $info;
          }
        }

        .btn-search {
          width: 32px;
          height: 32px;
          text-align: center;
          line-height: 32px;
          cursor: pointer;
          position: absolute;
          right: 6px;
          top: 0;

          > i {
            font-size: 14px;
          }

          &:hover {
            color: $primary;
          }
        }
      }
    }
  }
}

.upload-data {
  height: 32px;
  line-height: 32px;
  width: 75px;
  border-radius: 5px;
  color: $white;
  text-align: center;
  float: right;
  margin-right: 30px;
  background-color: $primary;
  cursor: pointer;

  &:hover {
    background-color: $darkPrimary;
    font-weight: 500;
  }

  > i {
    font-size: 18px;
    line-height: 30px;
    font-weight: 500;
    display: none;
  }
}

@include keyframes(icon-spin) {
  from {
    @include rotate(0);
  }
  to {
    @include rotate(359);
  }
}
.resource-switch {
  position: absolute;
  top: 42px;
}
.resource-switch li {
  float: left;
  padding: 0 3px 6px;
  margin-right: 26px;
  font-size: 14px;
}
.resource-switch .active {
  border-bottom: 2px solid #5089ff;
  color: #5089ff;
}
.resource-switch li:hover {
  cursor: pointer;
}
</style>
